var child_process = require('child_process');
var spawn = child_process.spawn;
var path = require("path");
var cmdstr = path.join(__dirname, "start.bat");
var shell = path.join(__dirname, "start.sh");
var http = require('http');
var R = require('ramda');
var os = require('os');
var util = require('../../util/util.js');
var PORT = 7777;
module.exports = {
    start: function(rootpath, port) {
        PORT = port;
        function winstart(ostype){
            return spawn(cmdstr,[__dirname, rootpath, port]);
        }
        function otherstart(ostype){
            return spawn(shell,[__dirname, util.parsePath(rootpath), port]);
        }
        return R.ifElse(R.equals("Windows_NT"),winstart,otherstart)(os.type());
    },
    req: function(file, dfiles, endfn) {
        dfiles = dfiles || [];
        var query = R.compose(R.join('&'), R.map(R.concat('dfiles=')));
        var isJsp = R.compose(R.equals(R.lastIndexOf('jsp', file)), R.subtract(R.__, 3), R.length);
        var rootpathfn = R.ifElse(isJsp,
            R.always('/jsp?file=' + file),
            R.always('/fmk?file=' + file));
        var dfilestr = query(dfiles);

        var pathfn = R.ifElse(R.isEmpty, R.always(rootpathfn(file)), R.concat(rootpathfn(file) + '&'));
        var path = pathfn(dfilestr);
        http.request({
            hostname: 'localhost',
            port: PORT,
            path: path
        }, function(resp) {
            var result = [];
            resp.on('data', function(chunk) {
                result.push(chunk);
            });
            resp.on('end', function() {
                endfn(result.join(''));
            });
            resp.on('error', function(e) {
              endfn('problem with request: ' + e.message);
            });
        }).end();
    }
}
